<template>
  <!-- <div style="width: 100%"> -->
    <div id="container" class="realMonitoring"></div>
    <!-- <div class=""></div>
  </div> -->
</template>
<style lang="scss">
.amap-info-content {padding: 0 !important;}
.infoWin {
    width: 440px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background-color: #fff;
    font-size: 12px;
    box-shadow: 0 0 7px #858383;
    position: relative;
    .infoWin-sharp {
      position: absolute;
      bottom: -8px;
      left: 50%;
      margin-left: -8px;
      border-left: 8px solid transparent;
      border-right: 8px solid transparent;
      border-top: 8px solid #fff;
    }
    .infoWin-top {
      display: flex;
      align-items: center;
      background-color: rgb(64, 150, 209);
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-left: 10px;
      box-sizing: border-box;
      >span { font-size: 14px; font-weight: 600; color: #fff; }
      .amap-info-close { top: 10px !important; }
      .infoWin-top-state {
        display: flex;
        align-items: center;
        >div { width: 8px; height: 8px; border-radius: 50%; background: #2e60f2;margin-left: 30px; }
        >span { font-size: 14px; color: #2e60f2; margin-left: 3px }
      }
    }
    .infoWin-layer1 {
      display: flex;
      .infoWin-layer1-left {
        flex: 1;
        >div {
          display: flex;
          height: 30px;
          >span {
            display: flex;
            align-items: center;
            &:nth-of-type(1) {
              flex: 0 0 80px;
              
              justify-content: center;
              background-color: #f1f1f1;
            }
            &:nth-of-type(2) {
              flex: 1;
              padding-left: 10px;
              box-sizing: border-box;
            }
          }
        }
      }
      .infoWin-layer1-right {
        flex: 0 0 194px;
        border-left: 1px solid rgb(214, 214, 214);
        
        img {
          width: 194px;
          height: 104px;
        }
      }
    }
    .infoWin-layer2 {
      display: flex;
      border-top: 1px solid rgb(214, 214, 214);
      height: 50px;
      >span {
        flex: 0 0 80px; 
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f1f1f1;
      }
      >div {
        flex: 1;
        padding: 5px 10px;
      }
    }

    .infoWin-layer3 {
      border-top: 1px solid rgb(214, 214, 214);
      display: flex;
      height: 40px;
      align-items: center;
      padding: 0 5px;
      .item { 
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: 10px;
        &:hover {
          background-color: #eee;
        }
        >img { width: 15px; height: 15px; margin-right: 5px; }
        >span { font-size: 12px; }
      }
      .line { height: 15px; border-right: 1px solid rgb(214, 214, 214); margin: 0 5px; }
    }

    .infoWin-line { border-bottom: 1px solid #e3dede; margin-top: 6px; }
    .infoWin-item { font-weight: 600; color: #565151;
      padding: 5px 0; font-size: 12px; display: flex; 
      &:nth-of-type(1) { margin-top: 10px; }  
      >div:nth-of-type(2) { line-height: 20px; }
    }
  }
</style>
<style lang="scss" scoped>
.realMonitoring {
  width: 100%;
  height: 100%;
}
</style>
<script>
import { dateFormat } from '@/util/date'

export default {
  data() {
    return {
      map: null,
      markerArr: [],
      infoWindow: null,
      currentChoosedCar: null,   //当前选中车
      runMassMarks: null,    //行驶车辆图层
      stopMassMarks: null,   //停止车辆图层
      offlineStopMassMarks: null,   //离线车辆图层
      labelLayer: null,    //标注图层
      cluster: null,
    }
  },
  watch: {
    currentChoosedCar(val) {
      // console.log('watch', val)
      this.$emit('chooseCar', val)
    }
  },
  methods: {
    //选择定位车辆
    choosedCar(obj) {
      if(obj && obj.location.lng && obj.location.lat) {
        this.currentChoosedCar = obj
        this.map.setCenter([obj.location.lng, obj.location.lat]);
        this.infoOpen(obj)
      }
    },

    //图层打点
    drawLayerMarket(data, layerName) {
      if(data.length == 0) {
        this[layerName] && this[layerName].clear()
        return
      }
      let imgName = ''
      if(layerName == 'runMassMarks')
        imgName = '车辆.png'
      else if(layerName == 'stopMassMarks')
        imgName = '停止.png'
      else 
        imgName = '离线车辆.png'

      let layerIndex = 0
      if(layerName == 'runMassMarks')
        layerIndex = 10
      else if(layerName == 'stopMassMarks')
        layerIndex = 9
      else
        layerIndex = 8
      const styleArr = new Array(361).fill().map((item,index) => {
        return {
          url: require(`../../../../public/img/bg/${imgName}`),
          anchor: new AMap.Pixel(0, 0),
          size: new AMap.Size(25, 25),
          rotation: layerName == 'runMassMarks' ? index : 0
        }
      })

      if(this[layerName]) {
        this[layerName].clear()
        this[layerName].setData(data)
      }
      else {
        this[layerName] = new AMap.MassMarks(data, {
          opacity:0.8,
          zIndex: layerIndex,
          cursor:'pointer',
          style: styleArr
        })
        this[layerName].setMap(this.map)
        this[layerName].on('click', e => {
          this.currentChoosedCar = e.data
          this.infoOpen(e.data)
        })
      }
    },

    //标注图层
    drawLabelLayer(data) {
      // if(data.length == 0)
      // {
      //   if(this.labelLayer)
      //   {
      //     this.labelLayer.hide()
      //     return
      //   }
      //   else
      //     this.labelLayer.show()
      // }

      const data1 = data.map(item => {
        return new AMap.LabelMarker({
            name: item.name,
            position: [item.location.lng, item.location.lat],
            zIndex: 10,
            text: {
                content: item.name + '   ' + (item.location.speed || 0) + 'km/h',
                direction: 'bottom',
                offset: [0, 20],
                style: {
                  fontSize: 12,
                  fontWeight: 'normal',
                  fillColor: '#fff',
                  padding: '2, 5',
                  backgroundColor: 'rgb(249,192,47)',
                  borderColor: '#fff',
                  borderWidth: 1,
                }
            }
        })
      })

      // if(this.labelLayer) {
      //   this.labelLayer.clear()
      //   this.labelLayer.add(data1)
      //   this.map.add(this.labelLayer);
      // }
      // else {
      if(this.labelLayer)
        this.labelLayer.clear()
      this.labelLayer = new AMap.LabelsLayer({
        zIndex: 6
      })
      
      this.labelLayer.add(data1)
      this.map.add(this.labelLayer);
      // }
    },

    //地图打点
    setMarket(data, currentNode, type) {
      try {
      // console.log('markerArr', this.markerArr, data)
      //移除所有打点
      if(this.markerArr.length > 0) {
        this.map.remove(this.markerArr)
      }
      
      if(data.filter(item => item.id == currentNode.id).length == 0) {
        if(this.infoWindow)
          this.infoWindow.close()
      }
      const pointData = data.filter(item => item.location.lng && item.location.lat).map((item, index) => {
        return {
          ...item,
          ...{
            lnglat: [item.location.lng, item.location.lat],
            style: item.location.direction ? parseInt(item.location.direction) : 0
          }
        }
      })
      
      // console.log('绘制地图打点')
      const runCarArr = pointData.filter(item => item.status == '1' && item.location.speed)
      const stopCarArr = pointData.filter(item => item.status == '1' && !item.location.speed)
      const offlineCarArr = pointData.filter(item => item.status == '2')
      // this.drawLayerMarket(runCarArr, 'runMassMarks')
      // this.drawLayerMarket(stopCarArr, 'stopMassMarks')
      // this.drawLayerMarket(offlineCarArr, 'offlineStopMassMarks')
      // this.drawLabelLayer(pointData)
      this.drawerCluster(pointData)
      
      if(currentNode.children) {
        let carObj = null
        if(offlineCarArr.length > 0)
          carObj = offlineCarArr[0]
        if(stopCarArr.length > 0)
          carObj = stopCarArr[0]
        if(runCarArr.length > 0)
          carObj = runCarArr[0]
        if(carObj)
          this.map.setZoomAndCenter(12, [carObj.location.lng, carObj.location.lat]);
      } else {
        //选择单个车
        const carObj = pointData.find(item => item.id == currentNode.id)
        if(carObj) {
          this.currentChoosedCar = carObj
          this.map.setCenter([carObj.location.lng, carObj.location.lat]);
          this.infoOpen(carObj)
        } else {
          if(this.currentChoosedCar) {
            this.map.setCenter([this.currentChoosedCar.location.lng, this.currentChoosedCar.location.lat]);
            this.infoOpen(this.currentChoosedCar)
          }
        }
      }

      window.historyPlayer = (deviceNo, vehicleNumber) => {
        this.$emit('historyPlay', deviceNo, vehicleNumber)
      }
      }
      catch(e) {
        console.log(e)
      }
      window.lookDetail = carId => { this.$emit('lookDetail', carId) }
      window.closeWin = () => { 
        this.currentChoosedCar = null
        this.infoWindow.close() 
      }
      
    },
    infoOpen(item) {
      const stateFunc = (type) => {
        if(type == 1)
          return '在线'
        if(type == 2)
          return '离线'
        if(type == 3)
          return '未激活'
      }
      const content = `<div class="infoWin">
        <div class="infoWin-sharp"></div>
          <div class="infoWin-top">
            <span>${item.name}</span>
            <a class="amap-info-close" href="javascript: void(0)" onclick="closeWin()">×</a>
            <div class="infoWin-top-state" style="display:none">
              <div></div>
              <span>${stateFunc(item.location.status)}</span>
            </div>
          </div>
          <div class="infoWin-layer1">
            <div class="infoWin-layer1-left">
              <div>
                <span>定位时间</span>
                <span>${dateFormat(new Date(item.location.locateTimeStr))}</span>
              </div>
              <div>
                <span>行驶速度</span>
                <span>${item.location.speed || 0}km</span>
              </div>
              <div>
                <span>今日里程</span>
                <span>${item.location.mileageToday || 0}km</span>
              </div>
              <div>
                <span>车辆状态</span>
                <span>${stateFunc(item.location.status)}</span>
              </div>
            </div>
            <div class="infoWin-layer1-right">
              <img src="${item.carPicUrl }" onerror="javascript:this.src='http://oss.sdland-sea.com/group1/M01/3A/AE/Cof8EmO_rz2AcxW1AAAc6KPKvkg378.jpg'" />
            </div>
          </div>
          <div class="infoWin-layer2">
            <span>地理位置</span>
            <div>${item.location.address}</div>
          </div>
          <div class="infoWin-layer3">
            <div class="item"  onclick="historyPlayer(${item.deviceNo}, '${item.name}')">
              <img src="http://oss.sdland-sea.com/group1/M01/3A/74/Cof8EWO-ExWATfPxAAADYJELVHs408.png" />
              <span>轨迹</span>
            </div>
            <div class="line"></div>
            <div class="item" onclick="lookDetail(${item.id})">
              <img src="http://oss.sdland-sea.com/group1/M01/3A/6E/Cof8EmO-E1mAOczCAAABo3-8Bvw612.png" />
              <span>详情</span>
            </div>
          </div>
          
        </div>`
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true,
        offset: new AMap.Pixel(0, -10), //默认窗体偏移量
      });
      this.infoWindow.setContent(content);
      this.infoWindow.open(this.map, [item.location.lng, item.location.lat]);
    },
    drawerCluster(pointData) {
      let markers = []
      if (pointData.length > 0) {
        pointData.forEach(item => {
          markers.push(new AMap.Marker({
            position: item.lnglat,
            // content: '<div style="background-color: hsla(180, 100%, 50%, 0.7); height: 24px; width: 24px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 1px;"></div>',
            offset: new AMap.Pixel(-5, -5)
        }))
        })
      }
      AMap.plugin('AMap.MarkerClusterer', () => {
        this.cluster = new AMap.MarkerClusterer(this.map, markers, {
          gridSize: 80
        });
      })
    }
  },
  mounted() {
    this.map = new AMap.Map('container', {
      center:[117.000923,36.675807],
      zoom: 5
    });
  }
}
</script>